package com.哈希表;

import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * 桶，用Linkset装
 */
class Bucket{
    List<Integer> container  ;
    public Bucket(){
        this.container  = new LinkedList<>();
    }
    public void add(int key){
        if(container.contains(key)){
            return;
        }
        container.add(key);
    }
    public boolean exit(int key){
        return container.contains(key);
    }
    public void del(int key){
        int index = container.indexOf(key);
        if(index == -1){
            return;
        }

        container.remove(index);
        
    }
}

/**
 * 哈希建
 */
public class MyHashSet {
    //桶数量
    Bucket[] buckets;
    //范围
    int keyRange;
    /** Initialize your data structure here. */
    public  MyHashSet() {
        //质数尽量避免哈希冲突
        keyRange = 769;
        buckets = new Bucket[keyRange];
        //将每个桶都激活
       for(int i = 0;i<buckets.length;i++){
           buckets[i] = new Bucket();
       }
    }

    /**
     * 哈希函数，用来确定桶的位置
     * @param key
     * @return
     */
    public int hash(int key){
        return key%keyRange;
    }

    /**
     * 添加
     * @param key
     */
    public void add(int key) {
        buckets[hash(key)].add(key);
    }

    /**
     * 删除
     * @param key
     */
    public void remove(int key) {
        buckets[hash(key)].del(key);
    }

    /** 是否存在*/
    public boolean contains(int key) {
        return buckets[hash(key)].exit(key);
    }
    public String toString(){
        StringBuilder builder = new StringBuilder();
        for(int i = 0 ;i<buckets.length;i++){
            builder.append(String.format("键:%s,桶{",i));
            buckets[i].container.forEach(item->{
                builder.append(item).append(",");
            });
            builder.append("}").append("\n");

        }
        return builder.toString();
    }

    public static void main(String[] args) {
        MyHashSet hash = new MyHashSet();
        hash.add(1);
        hash.add(2);
        hash.add(3);
       // hash.remove(1);
        System.out.println(hash.contains(1));
        System.out.println(hash.contains(2));
        System.out.println(hash.contains(5));
        hash.remove(1);
        System.out.println(hash.contains(1));
    }
}
